<template>
  <div class="app-container">
    <el-form
      class="formList"
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="80px"
    >
      <el-row>
        <el-form-item label="模板标题" prop="templateTitle">
          <el-input
            v-model="queryParams.templateTitle"
            placeholder="请输入模板标题"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>

        <!-- <el-form-item label="状态" prop="dataStatus">
          <el-select
            v-model="queryParams.dataStatus"
            placeholder="请选择状态"
            clearable
            size="small"
          >
            <el-option
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item> -->

        <el-form-item style="margin-left: 22px">
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="handleQuery"
            >搜索</el-button
          >
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
            >重置</el-button
          >
        </el-form-item>
      </el-row>
    </el-form>

    <el-row class="row-mbinfo">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['device:Template:add']"
          >新增</el-button
        >
      </el-col>

      <el-col :span="1.5" style="margin-left: 10px">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['device:Template:remove']"
          >删除</el-button
        >
      </el-col>

      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>
    <div class="divTable">
      <el-table
        border
        v-loading="loading"
        :data="TemplateList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />

        <el-table-column label="模板标题" align="center" prop="templateTitle" />
        <el-table-column label="模板类型" align="center" prop="templateTypeStr" />
        <el-table-column label="模板店铺" align="center" prop="storeName" />
        <el-table-column label="模板编号" align="center" prop="templateNo" />

        <el-table-column label="状态" align="center" prop="dataStatus">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.dataStatus"
              active-value="1"
              inactive-value="0"
              @change="handleStatusChange(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>

        <el-table-column
          label="修改时间"
          align="center"
          prop="updateTime"
          width="180"
          sortable
        >
          <template slot-scope="scope">
            <span>{{
              parseTime(scope.row.updateTime, "{y}-{m}-{d} {h}:{i}:{s}")
            }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">

            <el-button
              v-if="scope.row.dataStatus == '0'"
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['device:Template:remove']"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>
    <!-- 添加或修改模板/系列对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="750px"
      append-to-body
      @keyup.enter.native="submitForm"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="140px">
        <el-form-item label="模板标题" prop="templateTitle">
          <el-input
            v-model="form.templateTitle"
            placeholder="请输入模板标题"
            class="select-normal"
            maxlength="20"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="所属门店">
              <el-select v-model="form.platformUid" placeholder="请选择" size="small">
                <el-option v-for="item in storeList" :key="item.storeUid" :label="item.storeName"
                  :value="item.storeUid">
                </el-option>
              </el-select>
            </el-form-item>


        <el-form-item label="模板类型">
              <el-select v-model="form.templateType" placeholder="请选择" size="small">
                <el-option v-for="dict in options" :key="dict.dictValue" :label="dict.dictLabel"
                  :value="dict.dictValue">
                </el-option>
              </el-select>
            </el-form-item>

        <el-form-item label="模板编号" prop="deviceDesc">
          <el-input
            v-model="form.templateNo"
            placeholder="请输入模板编号"
            style="width: 400px"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listTemplate,
  getTemplate,
  delTemplate,
  addTemplate,
  updateTemplate,
  updateTemplateStatus,
} from "@/api/system/message";
import { listStoreSelect, listGroupSelect } from "@/api/platform/store";
import imageArraySize from "@/components/ImageUpload/imageArraySize";
export default {
  name: "Template",
  components: {
    imageArraySize,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      //选中数组的名字
      names: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 模板/系列表格数据
      TemplateList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 用于类别关联的分类显示
      dialogVisible: false,
      //常用状态数据字典
      statusOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        templateTitle: null,
        dataStatus: null,
      },
      storeList: [],
      options: [
      ],
      optionsA: [
        {
          value: "1",
          label: "能量",
        },
        {
          value: "0",
          label: "非能量",
        },
      ],
      // 表单参数
      form: {
        dialogImageUrl: "",
        dataPriority: "",
      },
      // 表单校验
      rules: {
        templateTitle: [
          {
            required: true,
            message: "模板名称不能为空",
            trigger: "blur",
          },
        ],
        dataPriority: [
          {
            required: true,
            message: "排序不能为空",
            trigger: "blur",
          },
        ],
      },
      defaultProps: {
        children: "children",
        label: "label",
      },
    };
  },
  created() {
    this.getList();
    this.getDicts("sys_data_status").then((response) => {
      this.statusOptions = response.data;
    });
    this.getDicts("template_type").then(response => {
            this.options = response.data;
        });
    listStoreSelect().then(response => {
      this.storeList = response.data;
    })
  },
  methods: {
    dataPriorityInput(value) {
      let js = value + "";
      return js.replace(/^(0+)|[^\d]+/g, "");
    },
    /** 查询模板/系列列表 */
    getList() {
      this.loading = true;
      listTemplate(this.queryParams).then((response) => {
        this.TemplateList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    handleRemove(file, fileList) {},
    handlePictureCardPreviewLogo(file) {
      this.logoUr = file.url;
      this.dialogVisible = true;
    },
    handlePictureCardPreviewImg(file) {
      this.deviceImage = file.url;
      this.dialogVisible = true;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 关联的取消按钮
    cancelTemplate() {
      this.openTemplate = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        templateTitle: null,
        logoUrl: null,
        deviceTemplate: null,
        deviceImage: null,
        dataPriority: 10,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 模板菜单 */
    getMenuTreeselect() {
      menuTreeselect().then((response) => {
        this.menuOptions = response.data;
      });
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.templateUid);
      this.names = selection.map((item) => item.templateTitle);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
      //用于禁用删除
      if (this.multiple == false) {
        for (var i = 0; i < selection.length; i++) {
          var element = selection[i];
          if ("1" === element.dataStatus) {
            this.multiple = true;
            break;
          }
        }
      }
    },
    // 状态修改
    handleStatusChange(row) {
      let text = row.dataStatus === "0" ? "无效" : "有效";
      this.$confirm(
        '确定要把模板名称为"' + row.templateTitle + '"设为' + text + "吗？",
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return updateTemplateStatus(row.templateUid, row.dataStatus);
        })
        .then(() => {
          this.msgSuccess("操作成功");
          this.getList();
        })
        .catch(function () {
          row.dataStatus = row.dataStatus === "0" ? "1" : "0";
        });
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加模板";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const templateUid = row.templateUid || this.ids;
      getTemplate(templateUid).then((response) => {
        this.form = response.data;
        console.log(this.form);
        this.open = true;
        this.title = "修改模板";
      });
    },
    /** 提交按钮 */
    submitForm() {

      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.templateUid != null) {
            updateTemplate(this.form).then((response) => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTemplate(this.form).then((response) => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const templateUids = row.templateUid || this.ids;
      const names = row.templateTitle || this.names;
      this.$confirm('是否确认删除模板名称为"' + names + '"的模板?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return delTemplate(templateUids);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(() => {});
    },

    /** 导出按钮操作 */
    // handleExport() {
    //   this.download(
    //     "device/Template/export",
    //     {
    //       ...this.queryParams,
    //     },
    //     `商品模板.xlsx`
    //   );
    // },
  },
};
</script>
<style lang="scss" scoped>
.treeOne {
  display: inline-block;
  margin-right: 200px;
}

.treeTwo {
  display: inline-block;
}

.image-rows {
  width: 80px;
  height: auto;
}
</style>
